import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * author: MaHX
 * date: 2019/9/17/22:54
 * description:
 * 用于解决多线程安全问题的方法：
 * synchronized（隐式锁 ）:
 * 1，同步代码块
 * <p>
 * 2，同步方法
 * <p>
 * 3,同步锁（jdk 1.5之后）
 * 注意：一个显示锁，需要通过lock（）上锁，必须通过unlock（）解锁
 **/
public class TestLock {
    public static void main(String args[]) {
        Ticket ticket = new Ticket();
        new Thread(ticket, "一号窗口").start();
        new Thread(ticket, "二号窗口").start();
        new Thread(ticket, "三号窗口").start();

    }

    static class Ticket implements Runnable {
        private int ticket = 100;
        private Lock lock = new ReentrantLock();

        @Override
        public void run() {
            while (ticket > 0) {
                try {
                    lock.lock();
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "完成售票，余票为:" + --ticket);
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
